/*
 * tools functions
 *
 */
#include "config.h"
#include "ebike-tools.h"
#include <WProgram.h>
#include <math.h>

// filtered input value
static double fADC[6] = {0,0,0,0,0,0};

//
//average filter 40ms for 1 analogue value
//
double fanalogRead(int pin, int wait){
  if (fADC[pin]==0)
    fADC[pin]=analogRead(pin);
  for (int i=0;i<10;i++){
    fADC[pin] = 0.90 * fADC[pin] + 0.10 * analogRead(pin); 
    delay(wait);               
  }
  return fADC[pin];
}


// Return RC high-pass filter output sample, 
// x input sample, x¹ last sample (n-1) 
// y¹ last output sample (n-1), 
// dt time interval, 
// RC time constant
float highpass(float x, float x1 , float y1, float dt, float RC){
   double alpha = RC / (RC + dt);
   return  alpha * y1 + alpha * (x - x1);
}


// Return RC low-pass filter output sample, 
// x input sample, 
// y¹ last output sample (n-1), 
// dt time interval, 
// RC time constant
float lowpass(float x, float y1, float dt, float RC){
   float alpha=dt/(RC + dt);
   //return  alpha * x + (1-alpha) * y1;
   return  y1 + alpha * (x - y1);
}


long read_vcc_ref() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}




